# 模块导入
from . import Feedback
from . import User
from . import database


# FeedBack表的mapper
class FeedBackMapper:
    # query
    # 根据feedback_id查找feedback项
    @staticmethod
    def query_feedback_id(feedback_id):
        return Feedback.query.get(feedback_id)

    # 查找feedback列表
    @staticmethod
    def query_all():
        return Feedback.query.filter().all()

    # 根据user_id查询feedback项
    @staticmethod
    def query_user_id(user_id):
        return Feedback.query.filter_by(user_id=user_id).all()

    # 根据username查询feedback项
    @staticmethod
    def query_username(username):
        userlist = User.query.filter_by(username=username).all()
        feedbacklist = []
        for user in userlist:
            feedback = Feedback.query.filter_by(user_id=user.user_id).first()
            if feedback is None:
                break
            feedbacklist.append(feedback)
        return feedbacklist

    # 根据username模糊查询collect项
    @staticmethod
    def query_username_like(keyword):
        userlist = User.query.filter(User.username.like('%'+keyword+'%')).all()
        feedbacklist = []
        for user in userlist:
            feedback = Feedback.query.filter_by(user_id=user.user_id).first()
            if feedback is None:
                break
            feedbacklist.append(feedback)
        return feedbacklist

    # 根据message模糊查询feedback项
    @staticmethod
    def query_message_like(keyword):
        return Feedback.query.filter(Feedback.message.like('%'+keyword+'%')).all()

    # insert
    # 增加一个feedback项
    @staticmethod
    def insert(user_id, message):
        feedback = Feedback(user_id=user_id, message=message)
        database.session.add(feedback)
        database.session.commit()
        return "insert success"

    # update
    # 更新feedback项
    @staticmethod
    def update(feedback_id, user_id, message):
        feedback = Feedback.query.get(feedback_id)
        feedback.user_id = user_id
        feedback.message = message
        database.session.commit()
        return "update success"

    # delete
    # 删除feedback项
    @staticmethod
    def delete(feedback_id):
        feedback = Feedback.query.get(feedback_id)
        database.session.delete(feedback)
        database.session.commit()
        return "delete success"
